import store from '@/store'
import axios from 'axios'
import { createRouter, createWebHashHistory, RouteRecordRaw, createMemoryHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },

  {
    path: '/login',
    name: 'Login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue'),
    meta: {
      redirectAlreadyLogin: true
    }
  },

  {
    path: '/register',
    name: 'Register',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Register.vue'),
    meta: {
      redirectAlreadyLogin: true
    }
  },

  {
    path: '/column/:id',
    name: 'columnDetail',
    component: () => import(/* webpackChunkName: "about" */ '../views/ColumnDetail.vue')
  },

  {
    path: '/create',
    name: 'create',
    component: () => import(/* webpackChunkName: "about" */ '../views/CreatePost.vue'),
    meta: { requiresLogin: true }
  },

  {
    path: '/post/:id',
    name: 'postDetail',
    component: () => import(/* webpackChunkName: "about" */ '../views/PostDetail.vue'),
    meta: { requiresLogin: false }
  },
]

const router = createRouter({
  history: createWebHashHistory(),  // createWebHashHistory()
  routes
})

router.beforeEach((to,from, next) => {
  console.log("router.beforeEach....");
  const { user, token } = store.state;
  const { requiresLogin, redirectAlreadyLogin} = to.meta;
  console.log("user==", user)
  if(!user.isLogin) {
    if(token) {
      // 登录成功后，每次刷新页面都要执行这个分支： 需要处理一下： 按照目前设计，使用sessionStore处理一下
      // 有token无用户信息： 发送请求获取用户信息
      axios.defaults.headers.common.Authorization = `Bear ${token}`
      console.log("有token无user.islogin");
      store.dispatch('fetchCurrentUser').then(userInfo => {
        // 已登录： 跳转login和resigser页面，直接返回首页；
        redirectAlreadyLogin? next("/") : next();
      }).catch(err => {
        console.error("error-getUserInfo ", err);
        // 获取用户信息失败，跳转登录页；同时清空token
        store.commit("logout");
        next('/login')
      })
    }else {
      // 未登录，也没token，跳转的页面是需要登录的页面，直接跳转去登录
      requiresLogin? next('/login'): next();
    }
  }else {
    // 已登录： 跳转login和resigser页面，直接返回首页；
    redirectAlreadyLogin? next("/") : next();
  }
})

router.beforeEach((to,from, next) => {
  console.log("router.beforeEach....");
 if(to.meta.requiresLogin  && !store.state.user.isLogin ) {
   //  next('/login')
   // 需要权限的页面，未登录跳转登录页
   next({name: 'Login'})
 }else if(to.meta.redirectAlreadyLogin && store.state.user.isLogin){
    // 已经登录，访问login跳转首页
    next('/')
 }else {
   next();
 }
})

// router.beforeEach((to, from, next) => {
//   const isLogin = store.state.user.isLogin
//   if (to.path === '/login') {
//     next()
//   } else {
       //next('/login')
//     isLogin ? next() : next({name: 'Login'})
//   }
// })



export default router
